package com.jml.zlhq.app.ui;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jml.zlhq.app.AppContext;
import com.jml.zlhq.app.BuildConfig;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.util.UIUtil;
import com.loopj.android.http.TextHttpResponseHandler;

public class WebTiXianTXActivity extends BaseActivity {
	
	private LinearLayout loadpage;
	private TextView loadText;
	private WebView webView;
	private String url;
	private Handler handler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
        		Log.i("==web url==", url);
        	
                if(msg.what!=200) {//主页不存在  
                    //载入本地assets文件夹下面的错误提示页面404.html  
                	loadText.setText("很抱歉，出错啦！"); 
                } else {  
                	Map<String,String> extraHeaders = new HashMap<String, String>();
            	    extraHeaders.put("APP","ZLHQ");	   
            	    Log.i("ZLHQ URL: ", url);
            		webView.loadUrl(url,extraHeaders);
            		//webView.loadUrl("http://m.51zlhq.com/member/login");
                }  
        }  
	}; 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hdtxtx_activity);	
		
		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		//LinearLayout rightLay = (LinearLayout) findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		//rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) findViewById(R.id.content_header_left_img);
		leftImage.setImageResource(R.drawable.back_selector);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setVisibility(View.GONE);
		TextView centerText = (TextView) findViewById(R.id.content_header_center_text);
		centerText.setText("提现提醒");
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setText("  ");
		TextView cityChosed = (TextView) findViewById(R.id.content_header_center_text2);
		cityChosed.setVisibility(View.GONE);
	
		webView = (WebView) findViewById(R.id.txtx_detail_web);
		webView.setVisibility(View.GONE);
		/*********           *********/
		loadpage = (LinearLayout)findViewById(R.id.load_info_lay);
		loadText = (TextView) findViewById(R.id.load_info);		
//		loadpage.setVisibility(View.VISIBLE);
		String pid = getIntent().getExtras().getString("pID");
		url = "http://m.51zlhq.com/member/timer?pid=" + pid + "&";
		/*********           *********/
		initWebView();
						
	}
	 
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.content_header_left_lay:
			finish();
			break;
	
		default:
			break;
		}
	}
	
	protected void clearCach(WebView webView) {
		webView.clearCache(true); 
		CookieSyncManager.createInstance(this);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeAllCookie();
		CookieManager.getInstance().removeSessionCookie();
		//cookieManager.setCookie("", "");//cookies是在HttpClient中获得的cookie  
		CookieSyncManager.getInstance().sync();
		CookieSyncManager.getInstance().startSync();
	}
	@SuppressLint("SetJavaScriptEnabled")
	private void initWebView(){
		
//		// 得到设置属性的对象
//		WebSettings webSettings = webView.getSettings();
//		// 使能JavaScript
//		webSettings.setJavaScriptEnabled(true);
//		// 支持中文，否则页面中中文显示乱码
//		webSettings.setDefaultTextEncodingName("UTF-8");
//        webSettings.setSaveFormData(false);  
//        webSettings.setSupportZoom(false);  
//        webSettings.setBlockNetworkImage(true);
//		clearCach(webView);
//		// 限制在WebView中打开网页，而不用默认浏览器
        webView.setHorizontalScrollBarEnabled(false);//水平不显示
        webView.setVerticalScrollBarEnabled(false); //垂直不显示
//        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); 
//        webView.setWebViewClient(new WebViewClient() {
//			@Override
//			public boolean shouldOverrideUrlLoading(WebView view, String url) {
//				webView.loadUrl(url);
//				return true;
//			}
//		});
//		
//		webView.setWebChromeClient(new EXWebChromeClient());
		webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		webView.setWebChromeClient(new EXWebChromeClient());
		WebSettings webSettings = webView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				webView.loadUrl(url);
				return true;
			}
		});
		webSettings
				.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		webSettings.setUseWideViewPort(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		webView.getSettings().setSavePassword(false);
		
		loadData(null);
	}
	@Override
	public void loadData(Map<String, String> param) {
		// TODO Auto-generated method stub

		Map<String, String> params = new HashMap<String, String>();
		AppContext appCon = (AppContext) getApplication();
		params.put("auth_token",appCon.getLoginUid());
		HttpService.getByText(URLs.HUODONG_GETTOKEN, params, new TextHttpResponseHandler() {
			@Override
			public void onSuccess(int arg0, Header[] arg1, String resultStr) {
				try {
					if(BuildConfig.DEBUG)Log.i("==result post==", resultStr);
					JSONObject result = new JSONObject(resultStr);
					System.out.println("result TOKRN :"+ result);
					if(result.getInt("status")==0){
						String token = result.getJSONObject("data").toString();
						System.out.println("tokrn:" + token);
						url = url + "BTOKEN=" + new JSONObject(token).getString("BTOKEN");
						handler.sendEmptyMessage(200);
					}else{
						if(pageIndex>0)pageIndex--;
					}				
					handler.sendEmptyMessage(1);
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
				UIUtil.ToastMessage(activity, "抱歉，访问失败");
			}
		});
	
	}
	@Override
	public void clearData() {
		// TODO Auto-generated method stub
		
	}	
	
	/** 
     * 继承WebChromeClient类 
     * 对js弹出框时间进行处理 
     *  
     */  
    private class EXWebChromeClient extends WebChromeClient {  
  
        /** 
         * 处理alert弹出框 
         */  
        @Override  
        public boolean onJsAlert(WebView view,String url, String message, JsResult result) {  
//            mReusultText.setText("Alert:"+message);  
//            //对alert的简单封装  
//            new AlertDialog.Builder(WebViewDemo.this).  
//                setTitle("Alert").setMessage(message).setPositiveButton("OK",  
//                new DialogInterface.OnClickListener() {  
//                    @Override  
//                    public void onClick(DialogInterface arg0, int arg1) {  
//                       //TODO  
//                   }  
//            }).create().show();  
//            result.confirm();  
            return super.onJsAlert(view, url, message, result);  
        }  
  
        /** 
         * 处理confirm弹出框 
         */  
        @Override  
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {  
//            mReusultText.setText("Confirm:"+message);  
//            result.confirm();  
            return super.onJsConfirm(view, url, message, result);  
        }  
  
        /** 
         * 处理prompt弹出框 
         */  
        @Override  
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {  
//            mReusultText.setText("Prompt input is :"+message);  
//            result.confirm();  
            return super.onJsPrompt(view, url, message, message, result);  
        }  
        
        @Override
        public void onProgressChanged(WebView view,int newProgress){
        	loadText.setText("玩命加载中\t"+newProgress+"%");
        	if(newProgress>=100){
        		//header.getBackground().setAlpha(0);//(activity.getResources().getColor(R.color.full_transparent));
        		loadpage.setVisibility(View.GONE);
        		webView.setVisibility(View.VISIBLE);
        		webView.getSettings().setBlockNetworkImage(false);
        		Log.i("ZLHQ", "页面加载完成");
        	}
        }    
        public boolean shouldOverrideUrlLoading(WebView view, String url) { 
            view.loadUrl(url); 
            //如果不需要其他对点击链接事件的处理返回true，否则返回false 
            return true; 
        } 
       
    }  
	
	/**
	 * 自定义的Android代码和JavaScript代码之间的桥梁类
	 * 
	 * @author 1
	 * 
	 */
//	public class WebAppInterface {
//		Context mContext;
//
//		/** Instantiate the interface and set the context */
//		WebAppInterface(Context c) {
//			mContext = c;
//		}
//
//		/** Show a toast from the web page */
//		// 如果target 大于等于API 17，则需要加上如下注解window.thirdLogin.login(param)
//		@JavascriptInterface
//		public void method(String type,String id) {
//			Log.i("====js====", type+","+id);
//		}
//	}
	
	private int getRespStatus(String url) {  
        int status = -1;  
        try {  
                HttpHead head = new HttpHead(url);  
                HttpClient client = new DefaultHttpClient();  
                HttpResponse resp = client.execute(head);  
                status = resp.getStatusLine().getStatusCode();  
        } catch (Exception e) {}  
        return status;  
	} 

}
